import React, { useState, useEffect } from 'react'
import { Button, Form, Input, Row, Col, Card, Select,message } from 'antd';
import TableList from './TableList';
import { getControllersList, GetlockTypes, GetlockersProduct, GetlockersUser,Specifications, Batch } from '../service'
const Batchgeneration = ({setFlag}) => {


  const [form] = Form.useForm();



  const [dataSource, setDataSource] = useState([])


  const Generate = () => {
    setDataSource([])

    form.validateFields().then(values => {

      console.log(values)
      // 一次性处理所有逻辑 性能最好 循环速度块 
      const optimizeLoop = () => {
        const excludeSet = values.exclude
          ? new Set(values.exclude.split(',').map(d => d.trim()))
          : new Set();

        const start = parseInt(values.start);
        const end = parseInt(values.end);
        const areaPrefix = values.physical_zone;

        const newEntries = [];

        for (let i = start; i <= end; i++) {
          const lastDigit = i % 10;

          if (excludeSet.has(lastDigit.toString())) continue;

          newEntries.push({
            "locker_name": i.toString(),
            "locker_number": i,
            "locker_product_class":values.variety ,
            "locker_spec_name": values.locker_spec_name,
            "locker_type": values.type,
            "locker_user_type": values.region,
            "physical_zone": areaPrefix
          })
        }

        return newEntries;
      };

      const newEntries = optimizeLoop();
      setDataSource(prevData => [...prevData, ...newEntries]);


    }).catch(errorInfo => {
      console.log('表单验证失败：', errorInfo);
    });


  }

  const Inbound = () => {
    // console.log(JSON.stringify(dataSource))
    if (dataSource.length === 0) {
      message.error('请添加数据');
      return;
    }

    Batch({lockers:dataSource}).then(res => {
      console.log(res)

      if (res.code === 0) {
        message.success('添加成功');
        setDataSource([]);
      } else {
        message.error(res.msg);
      }
    }).catch(errorInfo => {
    });

  };

  const [physicalZoneList, setphysicalZoneList] = useState([])

  const [lockerTypeList, setlockerTypeList] = useState([])

  const [lockerProductList, setlockerProductList] = useState([])

  const [lockerUserList, setlockerUserList] = useState([])

  const [SpecificationsList, setSpecificationsList] = useState([])

  useEffect(() => {
    getData()
  }, [])

  const getData = async () => {

    let data = await getControllersList()

    console.log(data.data.list)
    if(!data.data.list.length) return setphysicalZoneList([])
    let list = data.data.list.map(item => {
      return {
        label: item.physical_zone + "区",
        value: item.physical_zone
      }
    })
    setphysicalZoneList(list)

    GetlockTypes().then(res => {

      setlockerTypeList(res.data.map(item => {
        return {
          label: item.type_name,
          value: item.type_name
        }
      }))
    })

    GetlockersProduct().then(res => {

      setlockerProductList(res.data.map(item => {
        return {
          label: item.product_class,
          value: item.product_class
        }
      }))
    })

    GetlockersUser().then(res => {
    
      setlockerUserList(res.data.map(item => {
        return {
          label: item.user_type,
          value: item.user_type
        }
      }))
    })

    Specifications().then(res => { 
      console.log(res.data)
      setSpecificationsList(res.data.map(item => { 
        return {
          label: item.spec_name,
          value: item.spec_name
        }
      }))
    })
  }


  return (
    <>
      <Card>
        <Form
          layout="inline"
          form={form}
        >
          <Row gutter={[16, 16]} >
            {/* 第一行 */}
            <Col span={4.8}>
              <Form.Item
                label="区号"

                labelAlign="left"
                name="physical_zone"

                rules={[{ required: true, message: '请选择区号' }]}
              >
                <Select
                  placeholder="请选择区号"
                  onChange={async () => {


                  }}
                  style={{ width: '180px' }}
                  options={physicalZoneList}
                />
              </Form.Item>
            </Col>

            <Col span={4.8}>
              <Form.Item
                label="开始柜号"
                initialValue={8001}
                labelAlign="left"
                name="start"
                rules={[{ required: true, message: '请输入开始柜号' }]}
              >
                <Input type='number' placeholder="请输入开始柜号" min={1} />
              </Form.Item>
            </Col>

            <Col span={4.8}>
              <Form.Item
                label="结束柜号"
                initialValue={8010}
                labelAlign="left"
                name="end"
                rules={[{ required: true, message: '请输入结束柜号' }]}
              >
                <Input type='number' placeholder="请输入结束柜号" min={1} />
              </Form.Item>
            </Col>

            <Col span={4.8}>
              <Form.Item
                label="柜类型"

                labelAlign="left"
                name="type"
                rules={[{ required: true, message: '请选择柜类型' }]}
              >
                <Select

                  placeholder="请选择柜类型"
                  style={{ width: '180px' }}
                  options={lockerTypeList}
                />
              </Form.Item>
            </Col>

            <Col span={4.8}>
              <Form.Item
                label="柜品种"

                labelAlign="left"
                name="variety"
                rules={[{ required: true, message: '请选择柜品种' }]}
              >
                <Select

                  placeholder="请选择柜品种"
                  style={{ width: '180px' }}
                  options={lockerProductList}
                />
              </Form.Item>
            </Col>

            {/* 第二行 */}
            <Col span={4.8}>
              <Form.Item
                label="区域"

                labelAlign="left"
                name="region"
                rules={[{ required: true, message: '请选择区域' }]}
              >

                <Select

                  placeholder="请选择区域"
                  style={{ width: '180px' }}
                  options={lockerUserList}
                />
              </Form.Item>


            </Col>
            <Col span={4.8}>
              <Form.Item
                label="规格"

                labelAlign="left"
                name="locker_spec_name"
                rules={[{ required: true, message: '请选择规格' }]}
              >

                <Select

                  placeholder="请选择规格"
                  style={{ width: '180px' }}
                  options={SpecificationsList}
                />
              </Form.Item>


            </Col>
            <Col span={4.8}>
              <Form.Item
                label="排除数"

                labelAlign="left"
                name="exclude"
              >
                <Input placeholder="请输入排除数以 , 隔开" />
              </Form.Item>


            </Col>
            <Col span={4.8}>
              <Form.Item
                label=""

                labelAlign="left"
                name="exclude"
              >
                <div style={{ width: 240, display: 'flex', justifyContent: 'space-between', }}>
                  <div>
                    <Button type="primary" onClick={() => Generate()}>生成</Button>
                  </div>
                  <div>
                    <Button type="primary" onClick={() => Inbound()}>入库</Button>
                  </div>
                  <div><Button type="primary" onClick={()=>setFlag(true)}>返回</Button></div>
                </div>
              </Form.Item>


            </Col>


          </Row>
        </Form>


      </Card>
      <br />
      <TableList dataSource={dataSource} setDataSource={setDataSource} />

    </>
  )
}

export default Batchgeneration